package com.xhwl.centiotdata.suppliersystem.bailian;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.xhwl.centiotdata.pojo.constant.BaiLianConstant;
import com.xhwl.centiotdata.pojo.dto.bailian.CompanyBaiLianDTO;
import com.xhwl.centiotdata.service.cent.IBiCompanyCentService;
import com.xhwl.common.enums.bi.CompanyStatusEnum;
import com.xhwl.common.enums.bi.CompanyTypesEnum;
import com.xhwl.common.pojo.cent.bi.Company;
import com.xhwl.common.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author： lianghz
 * @Description：
 * @Date 2021/09/20/ 10:09
 */
@Service
public class CompanyBaiLianHandler {
    private static final Logger log = LoggerFactory.getLogger(CompanyBaiLianHandler.class);

    @Autowired
    private GeneralBaiLianHandler generalBaiLianHandler;

    @Autowired
    private IBiCompanyCentService companyCentService;

    /**
     * 同步公司信息
     *
     * @param projectId
     * @param ipAndPort
     */
    public void syncCompany(Integer projectId, String ipAndPort) {
        syncCompany(projectId, ipAndPort, false);
    }

    /**
     * 同步公司信息
     *
     * @param projectId
     * @param ipAndPort
     */
    public void syncCompany(Integer projectId, String ipAndPort, boolean needClearCategory) {
        List<Company> companyList = pullCompany(projectId, ipAndPort);
        if (!CollectionUtils.isEmpty(companyList)) {
            companyCentService.asyncInfo(companyList, needClearCategory);
        }
    }

    private static final String[] delPrefix = {"A-", "B-", "C-"};
    private static final String[] filterArr = {"待定", "不使用", "测试"};
    private static final String ENABLE_DEPARTMENT_LEVEL = "3";

    public List<Company> pullCompany(Integer projectId, String ipAndPort) {
        HashMap<String, Object> params = new HashMap<>();
        JSONObject resultObject = generalBaiLianHandler.post(ipAndPort + BaiLianConstant.DEPARTMENT_URL, params);
        String data = resultObject.getString("data");
        if (StringUtils.isEmpty(data)) {
            log.error("post path:{};params:{}; data is null !", ipAndPort + BaiLianConstant.DEPARTMENT_URL, JSON.toJSONString(params));
            return null;
        }
        List<CompanyBaiLianDTO> companyBaiLianDTOS = JSONObject.parseArray(data, CompanyBaiLianDTO.class);
        List<Company> companyList = companyBaiLianDTOS.stream()
                //数据过滤下，只添加3级店铺，待定的店铺不添加
                .filter(companyBaiLianDTO -> ENABLE_DEPARTMENT_LEVEL.equals(companyBaiLianDTO.getDepartmentLevel()))
                .filter(companyBaiLianDTO -> isEnableName(companyBaiLianDTO.getDepartmentName()))
                .map(companyBaiLianDTO -> {
                    Company company = new Company();
                    company.setProjectId(projectId);
                    company.setCode(companyBaiLianDTO.getDepartmentID());
                    // 由于第三方返回数据不合规，需要暴力处理
                    String departmentName = "";
                    if (companyBaiLianDTO.getDepartmentName().length() > 4) {
                        departmentName = companyBaiLianDTO.getDepartmentName().substring(4);
                    } else {
                        departmentName = companyBaiLianDTO.getDepartmentName();
                    }
                    //删除无用的前缀
                    departmentName = delPrefix(departmentName);
                    company.setName(departmentName);
                    company.setIngestionTime(new Date());
                    //设置店铺属性
                    company.setType(CompanyTypesEnum.getTypeByDesc(companyBaiLianDTO.getDepartmentAttr()));
                    //设置店铺状态
                    company.setStatus(CompanyStatusEnum.getStatusByDesc(companyBaiLianDTO.getDepartmentStatus()));
                    //设置供应商品类名称
                    company.setSupplierCategoryName(companyBaiLianDTO.getSupplierCategoryName());
                    return company;
                }).collect(Collectors.toList());
        return companyList;
    }

    private boolean isEnableName(String name) {
        if (StringUtils.isEmpty(name))
            return false;
        for (int i = 0; i < filterArr.length; i++) {
            if (name.contains(filterArr[i]))
                return false;
        }
        return true;
    }

    private String delPrefix(String name) {
        if (StringUtils.isEmpty(name))
            return name;
        for (int i = 0; i < delPrefix.length; i++) {
            String delPrefix = CompanyBaiLianHandler.delPrefix[i];
            if (name.startsWith(delPrefix)) {
                return name.replaceFirst(delPrefix, "");
            }
        }
        return name;
    }

}
